package com.iiapk.gridnew;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

import com.iiapk.grid.database.ArticleManager;
import com.iiapk.gridnew.domain.Article;
import com.iiapk.gridnew.view.MyView;

public class FavoriteArticleActivity extends Activity implements OnGestureListener{   
	
    private MyAdapter adapter;
    private ListView listView;
    private List<Article> list = new ArrayList<Article>();
    private ImageView refreshBT;
    private int lastItem;
    private boolean isRefreshFoot;
    private boolean loadBool=true;
    List<Article> _list;
    ImageView list_lazyload_img;
    View footerView;
    private UpdateDataTask updateTask;
    private RefreshTask refreshTask;
    GestureDetector gestureDetector;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_type_add);
        gestureDetector = new GestureDetector(this);
        
        footerView = View.inflate(this, R.layout.list_lazyloading, null);
        list_lazyload_img = (ImageView)footerView.findViewById(R.id.list_lazyload_img);
       
		findViewById(R.id.panel_header_homeBT).setOnClickListener(
				new OnClickListener(){
			@Override
			public void onClick(View v) {
				finish();
				overridePendingTransition(R.anim.hold,R.anim.push_bottom_out);
			}
		});
		
		refreshBT = (ImageView)findViewById(R.id.panel_header_refreshBT);
		refreshBT.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				beginRefreshTask();
			}
		});
		
		ArticleManager articleManager = new ArticleManager(this);
		
		_list = articleManager.select("");
		_list.get(0).imgR=R.drawable.test1;
		_list.get(1).imgR=R.drawable.test2;
		_list.get(2).imgR=R.drawable.test3;
		_list.get(3).imgR=R.drawable.test4;
		_list.get(4).imgR=R.drawable.test5;
		_list.get(5).imgR=R.drawable.test6;
		_list.get(6).imgR=R.drawable.test7;
		
		list.addAll(_list);
		list.addAll(_list);
        
        listView = (ListView)findViewById(R.id.list_type_add_listview);
        listView.addFooterView(footerView);
        adapter = new MyAdapter(this);
        listView.setAdapter(adapter);
        listView.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View view, MotionEvent e) {
            	 if (gestureDetector.onTouchEvent(e)) { 
                     return true; 
                 } 
                 return false; 
            }
        });
      listView.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Log.v("onItemClick", "onItemClick");
			}
        });
        listView.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				lastItem = firstVisibleItem + visibleItemCount;
				if(firstVisibleItem + visibleItemCount == totalItemCount){
					isRefreshFoot = true;
		        }else{
		            isRefreshFoot = false;
		        }
			}
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				 if(scrollState == OnScrollListener.SCROLL_STATE_IDLE && isRefreshFoot){
					 if(loadBool){
					 	loadBool = false; 
					 	beginUpdateTask();
					 }	
	            }
			}
		});
        
    }
    
    private void beginUpdateTask() {
		if (updateTask != null) {
			updateTask.cancel(true);
		}
		updateTask = new UpdateDataTask();
		updateTask.execute();
	}
    
    private void beginRefreshTask() {
		if (refreshTask != null) {
			refreshTask.cancel(true);
		}
		refreshTask = new RefreshTask();
		refreshTask.execute();
	}
    
	static class ViewHolder {
		TextView text;
		ImageView icon;
		TextView time;
	}
    
    class MyAdapter extends BaseAdapter{
    	
    	private LayoutInflater mInflater;
    	Context mContext;
    	private ViewHolder holder;
    	
    	public MyAdapter(Context c){
    		mInflater = LayoutInflater.from(c);
    		mContext=c;
    	}
		public int getCount() {			
			return list.size();
		}
		public Object getItem(int arg0) {
			return list.get(arg0);
		}
		public long getItemId(int arg0) {
			return arg0;
		}
		public View getView(int arg0, View contentView, ViewGroup arg2) {
			MyView view  = new MyView(mContext,null);
			/*view.setOnTouchListener(new OnTouchListener() {
                public boolean onTouch(View view, MotionEvent e) {
                	gestureDetector.onTouchEvent(e);
                    return false;
                }
            });*/
			return new MyView(mContext,null);
		}
    }
    
    class RefreshTask extends AsyncTask<String, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			refreshBT.setBackgroundResource(R.anim.main_loading);
			 AnimationDrawable frameAnimation=(AnimationDrawable)refreshBT.getBackground(); 
			    frameAnimation.start(); 
		}
		@Override
		protected Void doInBackground(String... params) {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			refreshBT.setBackgroundResource(R.drawable.tab_refresh_selector);
		}
	}
    
    class UpdateDataTask extends AsyncTask<String, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			footerView.setVisibility(View.VISIBLE);
			AnimationDrawable frameAnimation=(AnimationDrawable)list_lazyload_img.getBackground(); 
			frameAnimation.start();
		}
		@Override
		protected Void doInBackground(String... params) {
			try {
				Thread.sleep(2000);
				list.addAll(_list);
		        list.addAll(_list);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			adapter.notifyDataSetChanged();
			listView.setSelection(lastItem - 1);
			loadBool=true;
			footerView.setVisibility(View.INVISIBLE);	
		}
	}
    
    @Override
    protected void onPause() {
    	super.onPause();
    	overridePendingTransition(R.anim.hold,R.anim.push_bottom_out);
    }

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		Log.v("onSingleTapUp", "onSingleTapUp");
		return false;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		Log.v("onFling", "onFling");
		return false;
	}
    
}